package com.juyu.miliao.authentication.security;

import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.security.exception.IllegalDeviceNoFormatException;
import com.juyu.miliao.common.security.exception.IllegalPasswordFormatException;
import com.juyu.miliao.common.security.exception.IllegalUsernameFormatFormatException;
import com.juyu.miliao.common.security.exception.IllegalVerificationCodeFormatException;
import com.juyu.miliao.common.util.VerifyUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 和默认的UsernamePasswordAuthenticationFilter相同
 * 增加参数格式验证的功能
 * 用户名密码登录
 *
 * @author zc
 */
public class VerifyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public VerifyUsernamePasswordAuthenticationFilter(String filterProcessesUrl) {
        super(new AntPathRequestMatcher(filterProcessesUrl, "POST"));
    }

    public VerifyUsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/username", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //验证手机号
        String username = request.getParameter("username");
        if (username == null)
            throw new IllegalUsernameFormatFormatException();
        username = username.trim();
        if (!username.matches("^[0-9A-Za-z]{5,16}$"))
            throw new IllegalUsernameFormatFormatException("username:" + username);
        //验证密码
        String password = request.getParameter("password");
        if (password == null)
            throw new IllegalPasswordFormatException("password:" + password);
        password = password.trim();
        if (!password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"))
            throw new IllegalPasswordFormatException();

        CommonHead com = VerifyUtil.verifyCommonHead(request);

        UserNamePassWordRegisterToken authRequest = new UserNamePassWordRegisterToken(username, password,com);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
